/*************************************************************************
	> File Name: ls.cpp
	> Author: WangYiFei
	> Mail: 824537320@qq.com
	> Created Time: Sat 09 Jan 2021 09:50:10 PM CST
 ************************************************************************/

#include "head.h"
#include "func.h"

// 方法一览

// 参数一览
char fileName[1024];
int a_flag = 0;
int l_flag = 0;
int flag_of_mulDir = 0;
struct winsize sz;

int main(int argc, char **argv) {
    int opt;
    while ( (opt = getopt(argc, argv, "al")) != -1 ) {
        switch (opt) {
            case 'a':
                // printf("a found!\n");
                a_flag = 1;
                break;
            case 'l':
                // printf("b found!\n");
                l_flag = 1;
                break;
            default:
                fprintf(stderr, "Usage : %s -al\n", argv[0]);
                exit(1);
        }
    }
    // 不带参数对应
    if (argc == optind) {
        char buff[1024];
        getcwd(buff, sizeof(buff));
        ls_dir(buff);
        return 0;
    }
    if (argc - optind > 1) {
        flag_of_mulDir = 1;
    }
    // 获取窗口大小
    if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &sz) < 0) {
        perror("ioctl");
        exit(1);
    }
    // printf("x = %d, y = %d\n", sz.ws_col, sz.ws_row);

    // 开始处理参数
    for (int i = optind; i < argc; i++) {
        // printf(GREEN("%d = %s\n"), i, argv[i]);
        struct stat fileInfo;
        // 不存在对应的文件或者文件夹
        if (lstat(argv[i], &fileInfo) < 0) {
            char tmp[512];
            sprintf(tmp, "ls : %s", argv[i]);
            perror(tmp);
            // printf("ls : %s: No such file or directory\n", argv[i]);
            continue;
        }
        if (flag_of_mulDir) {
            (i != optind) && printf("\n");
            printf("%s:\n", argv[i]);
        }
        if (S_ISDIR(fileInfo.st_mode)) {
            ls_dir(argv[i]);
        } else {
            ls_file(argv[i]);
        }
        // printf("%d = %s\n", i, argv[i]);
    }

    return 0;
}
